//
//  ZMLoadingView.m
//  ZMKitDemo
//
//  Created by zm on 2018/6/19.
//  Copyright © 2018年 zm. All rights reserved.
//

#import "ZMLoadingView.h"
@interface ZMLoadingView ()
@property (nonatomic,strong) UIImageView *loadingImageView;
@end

@implementation ZMLoadingView

+(void)showInView:(UIView *)view {
    if (!view || ![view isKindOfClass:[UIView class]]) {
        return;
    }
    if (!ZMKitConfig.shared.loadingImageNames || ZMKitConfig.shared.loadingImageNames.count == 0) {
        return;
    }
    
    ZMLoadingView *loadingView = [[self alloc] initWithFrame:view.bounds];
    [view addSubview:loadingView];
}

+(void)dismissFromView:(UIView *)view {
    if (!view || ![view isKindOfClass:[UIView class]]) {
        return;
    }
    for (UIView *v in view.subviews) {
        if ([v isKindOfClass:[self class]]) {
            ZMLoadingView *loadingV = (ZMLoadingView *)v;
            if (loadingV.loadingImageView.isAnimating) {
                [loadingV.loadingImageView stopAnimating];
            }
            [loadingV removeFromSuperview];
            break;
        }
    }
}

-(instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self addSubview:self.loadingImageView];
        if (ZMKitConfig.shared.loadingImageNames.count == 0) {
            NSString *imageName = ZMKitConfig.shared.loadingImageNames.firstObject;
            self.loadingImageView.image = [UIImage imageNamed:imageName];
        }else{
            NSMutableArray *images = [[NSMutableArray alloc] init];
            [ZMKitConfig.shared.loadingImageNames enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSString *imageName = ZMKitConfig.shared.loadingImageNames[idx];
                UIImage *img = [UIImage imageNamed:imageName];
                [images addObject:img];
            }];
            self.loadingImageView.animationImages = images;
            [self.loadingImageView startAnimating];
        }
    }
    return self;
}

-(UIImageView *)loadingImageView {
    if (!_loadingImageView) {
        _loadingImageView = [[UIImageView alloc] init];
        _loadingImageView.frame = self.bounds;
    }
    return _loadingImageView;
}




@end
